package com.example.demo.jpa.config.schedule;

import com.example.demo.jpa.customer.dto.CustomerCommand;
import com.example.demo.jpa.customer.dto.CustomerDTO;
import com.example.demo.jpa.person.dto.PersonCommand;
import com.example.demo.jpa.person.dto.PersonDTO;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.hc.client5.http.classic.methods.HttpDelete;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.classic.methods.HttpPut;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import uk.co.jemos.podam.api.PodamFactory;

import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;

@Component
public class PersonScheduleJob {

    private static final Logger logger = LoggerFactory.getLogger(PersonScheduleJob.class);
    CloseableHttpClient httpClient = HttpClients.createDefault();

    @Autowired
    PodamFactory podamFactory;

    @Scheduled(cron = "0 0/1 * * * ? ")
    public void callRoll() throws JsonProcessingException {
        int loop = ThreadLocalRandom.current().nextInt(6, 15);
        for (int i = 0; i < loop; i++) {
            int id = ThreadLocalRandom.current().nextInt(1, 8);
            HttpGet httpGet = new HttpGet("http://localhost:8081/person/"+id);
            int index = ThreadLocalRandom.current().nextInt(0, UserAgent.values().length);
            httpGet.addHeader("User-Agent", UserAgent.values()[index].toString());
            httpGet.addHeader("TrackingId", UUID.randomUUID().toString().replace("-",""));

            try {
                httpClient.execute(httpGet,response -> {
                    logger.info(response.getCode() + " " + response.getReasonPhrase());
                    final HttpEntity entity2 = response.getEntity();
                    // do something useful with the response body
                    // and ensure it is fully consumed
                    EntityUtils.consume(entity2);
                    return null;});
            } catch (Exception e) {
                logger.error("", e);
            }
        }

        HttpPost httpPost = new HttpPost("http://localhost:8081/person");
        PersonCommand customInfo = podamFactory.manufacturePojo(PersonCommand.class);
        ObjectMapper mapper = new ObjectMapper();
        StringEntity entity = new StringEntity(mapper.writeValueAsString(customInfo), ContentType.APPLICATION_JSON);
        httpPost.setEntity(entity);
        PersonDTO dto = null;
        try {
            dto = httpClient.execute(httpPost,response -> {
                logger.info(response.getCode() + " " + response.getReasonPhrase());
                final HttpEntity entity2 = response.getEntity();
                // do something useful with the response body
                // and ensure it is fully consumed
                String res = EntityUtils.toString(entity2);
                return mapper.readValue(res, PersonDTO.class);
                });
        } catch (Exception e) {
            logger.error("", e);
        }
        if (Objects.nonNull(dto)){
            HttpPut httpPut = new HttpPut("http://localhost:8081/person/"+dto.getId());
            customInfo = podamFactory.manufacturePojo(PersonCommand.class);
            StringEntity putEntity = new StringEntity(mapper.writeValueAsString(customInfo), ContentType.APPLICATION_JSON);
            httpPut.setEntity(putEntity);
            try {
                dto = httpClient.execute(httpPut,response -> {
                    logger.info(response.getCode() + " " + response.getReasonPhrase());
                    final HttpEntity entity2 = response.getEntity();
                    // do something useful with the response body
                    // and ensure it is fully consumed
                    String res = EntityUtils.toString(entity2);
                    return mapper.readValue(res, PersonDTO.class);
                });
            } catch (Exception e) {
                logger.error("", e);
            }


        }

        delete();

    }


    private void delete(){
        int loop = ThreadLocalRandom.current().nextInt(1, 4);
        for (int i = 0; i < loop; i++) {
            int id = ThreadLocalRandom.current().nextInt(1, 8);
            HttpDelete httpGet = new HttpDelete("http://localhost:8081/person/"+id);
            httpGet.addHeader("User-Agent", "Schedule");
            httpGet.addHeader("TrackingId", UUID.randomUUID().toString().replace("-",""));

            try {
                httpClient.execute(httpGet,response -> {
                    logger.info(response.getCode() + " " + response.getReasonPhrase());
                    final HttpEntity entity2 = response.getEntity();
                    // do something useful with the response body
                    // and ensure it is fully consumed
                    EntityUtils.consume(entity2);
                    return null;});
            } catch (Exception e) {
                logger.error("", e);
            }
        }
    }

}
